
package com.eascs.crm.loanstart.controller;

import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
import java.util.List;
import java.util.Map;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;

import com.alibaba.dubbo.config.annotation.Reference;
import com.eascs.admin.o2o.badloan.entity.O2oCacleEntity;
import com.eascs.admin.o2o.badloan.service.O2oCancleServiceImpl;
import com.eascs.admin.o2o.loan.entity.O2oLoanUserEntity;
import com.eascs.admin.o2o.loan.entity.O2oLoanapplyEntity;
import com.eascs.admin.o2o.loan.service.O2oLoanUserService;
import com.eascs.admin.o2o.loan.service.O2oLoanapplyService;
import com.eascs.admin.o2o.recommend.entity.O2oRecommendEntity;
import com.eascs.admin.o2o.recommend.service.O2oRecommendService;
import com.eascs.admin.o2o.zx.service.IO2oZxService;
import com.eascs.app.log.Logger;
import com.eascs.app.log.LoggerFactory;
import com.eascs.common.util.StringUtil;
import com.eascs.crm.common.custnew.entity.CustomerEntity;
import com.eascs.crm.common.custnew.service.CustomerService;
import com.eascs.crm.loanstart.form.CustomerBasicInfoForm;
import com.eascs.crm.loanstart.service.LoanStartServiceImpl;
import com.eascs.crm.nsEditDetail.service.CustomerInfoService;
import com.eascs.crm.nsEditDetail.vo.CustomerBasicVo;
import com.eascs.site.controller.BaseRestController;
import com.eascs.site.view.BaseRestResult;
import com.eascs.site.view.HtmlRestResult;
import com.eascs.site.view.ViewContext;
import com.eascs.web.sso.User;
import com.eascs.web.sso.UserHolder;
import com.eascs.web.url.UrlHelper;

@Controller
@RequestMapping("/rloanstart")
public class LoanStartRestController extends BaseRestController {
	private final Logger logger = LoggerFactory.getLogger(LoanStartRestController.class);
	@Reference
	CustomerService customerService;
	@Autowired
	LoanStartServiceImpl loanStartService;
	@Autowired
	private O2oLoanapplyService o2oLoanapplyService;
	@Autowired
	private O2oLoanUserService o2oLoanUserService;
	@Autowired
	private CustomerInfoService customerInfoService;
	@Autowired
	O2oCancleServiceImpl o2oCancleServiceImpl;
	@Autowired
	IO2oZxService o2oZxService;
	@Autowired
	O2oRecommendService o2oRecommendService;

	/**
	 * @Description:
	 * 				<p>
	 *               根据客户身份证查询贷款次数
	 *               </p>
	 * @author CXW
	 * @date 2017年7月14日 上午11:02:30
	 * @version V1.0
	 */
	@RequestMapping(value = "/checkLoan")
	public BaseRestResult<?> checkLoan(String idCard) {
		idCard = idCard.trim();
		O2oRecommendEntity entity = o2oRecommendService.findEntityByCard(idCard);
		if (null != entity) {
			User user = UserHolder.getUser();
			if (!entity.getOperatorNo().equals(user.getNo())) {
				return BaseRestResult.warn("is_recomment_r");
			}
		}
		O2oLoanUserEntity loanUserEntity = o2oLoanapplyService.getLoanId(idCard);
		logger.info("根据用户身份证查询用户是否存在贷款，身份证：【{}】，查询结果：【{}】", idCard, loanUserEntity);
		if (null != loanUserEntity) {
			List<O2oLoanapplyEntity> list = o2oLoanapplyService.findByLoanId(loanUserEntity.getLoanId());
			if (null != list && list.size() > 0) {
				for (O2oLoanapplyEntity o2oLoanapplyEntity : list) {
					O2oCacleEntity cacleEntity = o2oCancleServiceImpl.findByLoanapplyId(o2oLoanapplyEntity.getLoanapplyNo());
					if (null != cacleEntity && !StringUtil.isEmpty(cacleEntity.gettVetoTerm())) {
						Calendar cal = Calendar.getInstance();
						// 下面的就是把当前日期加一个月
						cal.setTime(cacleEntity.gettTime());
						cal.add(Calendar.MONTH, Integer.parseInt(cacleEntity.gettVetoTerm()));
						SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
						String ttime = format.format(cal.getTime()); // 作废限制到期时间
						String nowtime = format.format(Calendar.getInstance().getTime());// 当前时间
						if (compare_date(ttime, nowtime) != -1) {
							return BaseRestResult.warn("该客户申请的贷款单（" + o2oLoanapplyEntity.getBillCode() + "）在" + format.format(cacleEntity.gettTime()) + "被否决，限制期限是" + cacleEntity.gettVetoTerm() + "个月。");
						}
					}
				}
			}
			int o2oI = o2oLoanapplyService.checkLoapply(loanUserEntity.getLoanId());
			if (o2oI > 0) {
				// 该借款人在新系统中已存在贷款单
				return BaseRestResult.warn("is_user_loan");
			}
			// 检查客户是否有担保的单为结清
			int count = o2oLoanUserService.getCheckCountD(loanUserEntity.getDocumentNo());
			if (count > 0) {
				// 该客户有未结清的担保单，不能申请贷款
				return BaseRestResult.warn("is_user_danbao_loan");
			}
			// 新系统配偶校验
			O2oLoanUserEntity suporSeEntity = o2oLoanUserService.queryById(loanUserEntity.getLoanId());
			logger.info("根据用户身份证查询配偶是否存在贷款，身份证：【{}】，查询结果：【{}】", idCard, suporSeEntity);
			if (null != suporSeEntity) {
				int o2oS = o2oLoanapplyService.checkSpouse(suporSeEntity.getLoanId());
				if (o2oS > 0) {
					// 该借款人的配偶在新系统中已存在贷款单
					return BaseRestResult.warn("is_userspouse_loan");
				}

				int countS = o2oLoanapplyService.checkSpouse(suporSeEntity.getDocumentNo());
				if (countS > 0) {
					// 该客户配偶有未结清的担保单，不能申请贷款
					return BaseRestResult.warn("is_userspouse_danbao_loan");
				}
			}
		}
		return BaseRestResult.warn("success");

	}

	/**
	 * @Description:
	 * 				<p>
	 *               两个string类型的日期比较大小
	 *               </p>
	 * @author CXW
	 * @date 2017年6月16日 下午4:11:24
	 * @param date1作废限制到期时间，date2当前时间
	 * @version V1.0
	 */
	public static int compare_date(String date1, String date2) {
		DateFormat df = new SimpleDateFormat("yyyy-MM-dd");
		try {
			Date dt1 = df.parse(date1);
			Date dt2 = df.parse(date2);
			if (dt1.getTime() > dt2.getTime()) {// dt1 在dt2前
				return 1;
			} else if (dt1.getTime() < dt2.getTime()) {// dt1在dt2后
				return -1;
			} else {// dt1相等dt2
				return 0;
			}
		} catch (Exception exception) {
			exception.printStackTrace();
		}
		return 0;
	}

	@RequestMapping(value = "/saveOrupdateCustomerBasicInfo")
	public BaseRestResult<?> saveOrupdateCustomerBasicInfo(CustomerBasicInfoForm cbiForm) {
		BaseRestResult<?> result = null;
		Map<String, String> results = loanStartService.saveOrupdateCustomerBasicInfo(cbiForm);
		String flag = results.get("returnFlag");
		String customerId = results.get("customerId");
		if ("success".equals(flag)) {
			if (StringUtil.isNotBlank(cbiForm.getSaveType())) {
				result = BaseRestResult.redirect("/loanapply/addloan?customerId=" + customerId + "&loanType=" + cbiForm.getSaveType());
			}
		} else {
			result = BaseRestResult.warn(flag);
		}
		return result;
	}

	/**
	 * @Title:
	 * @Description: 客户信息模块(读取crm的)
	 * @author 余勇
	 * @return
	 * @return String
	 * @throws @date
	 *             2017年7月4日 下午2:17:31
	 */
	@RequestMapping("/view")
	public BaseRestResult<String> loanView(String customerId) {
		CustomerEntity customer = customerService.queryCustomerEntityByCustomerId(customerId);
		ViewContext.put("vo", customer);
		return HtmlRestResult.html("/loanstart/loanerView");
	}

	/**
	 * @Title:
	 * @Description: 客户信息模块(读取service的)
	 * @author 余勇
	 * @return
	 * @return String
	 * @throws @date
	 *             2017年7月4日 下午2:17:31
	 */
	@RequestMapping("/serviceView")
	public BaseRestResult<String> loanServiceView(String loanapplyNo, String type, String approvalStatus) {
		O2oLoanapplyEntity o2oLoanapplyEntity = o2oLoanapplyService.findById(loanapplyNo);
		/**** 查询service主借款人和配偶信息 ****/
		O2oLoanUserEntity customer = o2oLoanUserService.findById(o2oLoanapplyEntity.getLoanId(), loanapplyNo);
		O2oLoanUserEntity customer_sensitive = o2oLoanUserService.findById_sensitive(o2oLoanapplyEntity.getLoanId(), loanapplyNo);//脱敏
		O2oLoanUserEntity customerMate = o2oLoanUserService.findSpouseId(o2oLoanapplyEntity.getLoanId(), loanapplyNo);
		O2oLoanUserEntity customerMate_sensitive = o2oLoanUserService.findSpouseId_sensitive(o2oLoanapplyEntity.getLoanId(), loanapplyNo);//脱敏
		// 扩展信息
		CustomerBasicVo customerBasicVo = null;
		if (customerMate != null) {
			customerBasicVo = customerInfoService.queryCustomerById(customer.getId(), customerMate.getId());
		} else {
			customerBasicVo = customerInfoService.queryCustomerById(customer.getId(), null);
		}

		ViewContext.put("customerBasicVo", customerBasicVo);
		ViewContext.put("customer", customer);
		ViewContext.put("customer_sensitive", customer_sensitive);
		ViewContext.put("customerMate", customerMate);
		ViewContext.put("customerMate_sensitive", customerMate_sensitive);
		ViewContext.put("type", type);
		ViewContext.put("approvalStatus", approvalStatus);
		return HtmlRestResult.html("/loanstart/loanerServiceView");
	}
	
	/**
	 * CXW 显示征信查询详情客户联系电话和证件号码
	 * @param id
	 * @return
	 */
	@RequestMapping("/show_userinfo")
	public BaseRestResult<String> show_window(String id) {
		O2oLoanUserEntity o2oLoanUserEntityZx = o2oLoanUserService.queryById(id);
		ViewContext.put("vo", o2oLoanUserEntityZx);
		return HtmlRestResult.popHtmlFragment("/o2ozx/zx_show_info");
	}

	/**
	 * @Title: checkRefinance
	 * @Description:续贷校验
	 * @author 张庆奇
	 * @param loanapplyNo
	 * @return
	 * @return BaseRestResult<String>
	 * @throws @date
	 *             2017年8月8日 上午10:06:47
	 */
	@RequestMapping("/checkRefinance")
	public BaseRestResult<String> checkRefinance(String loanapplyNo) {
		O2oLoanapplyEntity apply = o2oLoanapplyService.findById(loanapplyNo);
		O2oLoanUserEntity user = o2oLoanapplyService.findLoanUserEntity(loanapplyNo, apply.getLoanId());
		if (null != user) {

			List<O2oLoanapplyEntity> list = o2oLoanapplyService.findByLoanId(user.getLoanId());
			if (null != list && list.size() > 0) {
				for (O2oLoanapplyEntity o2oLoanapplyEntity : list) {
					// 1.当否决客户的时候
					if (o2oLoanapplyEntity.getWfType().equals("T")) {
						O2oCacleEntity cacleEntity = o2oCancleServiceImpl.findByLoanapplyId(o2oLoanapplyEntity.getLoanapplyNo());
						if (null != cacleEntity && !StringUtil.isEmpty(cacleEntity.gettVetoTerm())) {
							Calendar cal = Calendar.getInstance();
							// 下面的就是把当前日期加一个月
							cal.setTime(cacleEntity.gettTime());
							cal.add(Calendar.MONTH, Integer.parseInt(cacleEntity.gettVetoTerm()));
							SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
							String ttime = format.format(cal.getTime()); // 作废限制到期时间
							String nowtime = format.format(Calendar.getInstance().getTime());// 当前时间
							if (compare_date(ttime, nowtime) != -1) {
								return BaseRestResult.warn("该客户申请的贷款单（" + o2oLoanapplyEntity.getBillCode() + "）在" + format.format(cacleEntity.gettTime()) + "被否决，限制期限是" + cacleEntity.gettVetoTerm() + "个月。");
							}
						}
					} else {
						int o2oI = o2oLoanapplyService.checkLoapply(user.getLoanId());
						if (o2oI > 0) {
							// 该借款人在新系统中已存在贷款单
							return BaseRestResult.warn("该客户有贷款单未结清，不能续贷");
						}
						// 检查客户是否有担保的单为结清
						int count = o2oLoanUserService.getCheckCountD(user.getDocumentNo());
						if (count > 0) {
							// 该客户有未结清的担保单，不能申请贷款
							return BaseRestResult.warn("该客户有担保的贷款未结清，不能续贷");
						}

					}
				}
			}
		}

		return BaseRestResult.redirect(UrlHelper.build("/loanstart/search?idCard=" + user.getDocumentNo()));

	}

}
